import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/User/Users'
import Rights from '../components/Power/Rights'
import Roles from '../components/Power/Roles'
import GoodsList from '../components/goods/List'
import Cate from '../components/goods/Cate'
import OrderList from '../components/order/List'
import params from '../components/goods/params'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: '/params',
        component: params
      },
      {
        path: '/goods',
        component: GoodsList
      },
      {
        path: '/orders',
        component: OrderList
      },
      {
        path: '/categories',
        component: Cate
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 利用路由导航守卫控制访问权限，
// 拿到路由对象，给对象挂载一个路由导航守卫beforeEach
router.beforeEach((to, from, next) => {
  // to:将要访问的路径
  // form：代表从哪个路径跳转而来
  // next：是一个函数，表示放行  next（）表示放行，next（‘/login‘）表示强制跳转到导航页
  if (to.path === '/login') return next()
  // 来判断当时用户访问的页面，若为登陆页面就没事，
  // 若为其他接口页面要通过是否携带token来判断是否已经登陆成功，若没有登录，但直接通过URL访问页面，就要强制返回到登陆页面
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
